package com.reservation.controller;

import com.reservation.entity.User;
import com.reservation.entity.Venue;
import com.reservation.service.VenueService;
import com.reservation.util.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/venue")
public class VenueController {
    
    @Autowired
    private VenueService venueService;
    
    @Autowired
    private HttpServletRequest request;

    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize,
                       Model model, HttpSession session) {
        //User user = (User) session.getAttribute("user");
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(pageNum);
        pageParam.setPageSize(pageSize);
        
        List<Venue> venues = venueService.findByPage(pageParam);
        model.addAttribute("venues", venues);
        model.addAttribute("pageParam", pageParam);
        return "venue/list";
    }

    @GetMapping("/add")
    public String add() {
        return "venue/add";
    }

    @PostMapping("/add")
    public String add(@ModelAttribute Venue venue, @RequestParam("image") MultipartFile image) {
        if (!image.isEmpty()) {
            try {
                String originalFilename = image.getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFilename = UUID.randomUUID().toString() + extension;
                
                // 获取webapp目录的绝对路径
                String webappPath = request.getServletContext().getRealPath("/");
                System.out.println("Webapp path: " + webappPath);
                
                // 创建upload目录
                String uploadDir = webappPath + "upload/";
                System.out.println("Upload directory: " + uploadDir);
                
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    boolean created = dir.mkdirs();
                    System.out.println("Upload directory created: " + created);
                    System.out.println("Directory exists after creation: " + dir.exists());
                }
                
                File file = new File(uploadDir + newFilename);
                System.out.println("File path: " + file.getAbsolutePath());
                System.out.println("File parent exists: " + file.getParentFile().exists());
                System.out.println("File parent is directory: " + file.getParentFile().isDirectory());
                System.out.println("File parent is writable: " + file.getParentFile().canWrite());
                
                image.transferTo(file);
                System.out.println("File exists after transfer: " + file.exists());
                System.out.println("File size: " + file.length());
                
                venue.setImagePath("/upload/" + newFilename);
            } catch (IOException e) {
                System.out.println("Error saving file: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        venue.setCreateTime(new Date());
        venueService.save(venue);
        return "redirect:/venue/list";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        Venue venue = venueService.findById(id);
        model.addAttribute("venue", venue);
        return "venue/edit";
    }

    @PostMapping("/edit")
    public String edit(@ModelAttribute Venue venue, @RequestParam(value = "image", required = false) MultipartFile image) {
        // 获取原始场馆信息，保留原有状态
        Venue originalVenue = venueService.findById(venue.getId());
        venue.setStatus(originalVenue.getStatus());
        venue.setCreateTime(originalVenue.getCreateTime());
        
        if (image != null && !image.isEmpty()) {
            try {
                String originalFilename = image.getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFilename = UUID.randomUUID().toString() + extension;
                
                // 获取webapp目录的绝对路径
                String webappPath = request.getServletContext().getRealPath("/");
                System.out.println("Webapp path: " + webappPath);
                
                // 创建upload目录
                String uploadDir = webappPath + "upload/";
                System.out.println("Upload directory: " + uploadDir);
                
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    boolean created = dir.mkdirs();
                    System.out.println("Upload directory created: " + created);
                    System.out.println("Directory exists after creation: " + dir.exists());
                }
                
                File file = new File(uploadDir + newFilename);
                System.out.println("File path: " + file.getAbsolutePath());
                System.out.println("File parent exists: " + file.getParentFile().exists());
                System.out.println("File parent is directory: " + file.getParentFile().isDirectory());
                System.out.println("File parent is writable: " + file.getParentFile().canWrite());
                
                image.transferTo(file);
                System.out.println("File exists after transfer: " + file.exists());
                System.out.println("File size: " + file.length());
                
                venue.setImagePath("/upload/" + newFilename);
            } catch (IOException e) {
                System.out.println("Error saving file: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            // 如果没有上传新图片，保持原有图片路径
            venue.setImagePath(originalVenue.getImagePath());
        }
        
        venueService.update(venue);
        return "redirect:/venue/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        venueService.deleteById(id);
        return "redirect:/venue/list";
    }

    @GetMapping("/updateStatus/{id}")
    public String updateStatus(@PathVariable Integer id, @RequestParam String status) {
        venueService.updateStatus(id, status);
        return "redirect:/venue/list";
    }

    @RequestMapping("/image/download/{filename}")
    public void downloadImage(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {
        String uploadDir = "D:/upload/";
        File file = new File(uploadDir + filename);
        
        if (file.exists()) {
            response.setContentType("image/jpeg");
            try (FileInputStream fis = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }
        }
    }
} 